<template>
  <div>
    <h2 class="title">历史趋势（浊度/转速/频率）</h2>
    <div ref="el" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useDataStore } from '../stores/dataStore';

const el = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;
const store = useDataStore();

function render() {
  if (!el.value) return;
  if (!chart) chart = echarts.init(el.value);
  const data = store.history;
  const times = data.map(d => new Date(d.timestamp).toLocaleTimeString());
  chart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['浊度', '转速', '频率'] },
    grid: { left: 40, right: 20, top: 30, bottom: 30 },
    xAxis: { type: 'category', data: times },
    yAxis: [
      { type: 'value', name: 'NTU' },
      { type: 'value', name: 'rpm', alignTicks: true },
      { type: 'value', name: 'Hz', alignTicks: true }
    ],
    series: [
      { name: '浊度', type: 'line', yAxisIndex: 0, data: data.map(d => d.turbidityNTU), smooth: true },
      { name: '转速', type: 'line', yAxisIndex: 1, data: data.map(d => d.pumpRpm), smooth: true },
      { name: '频率', type: 'line', yAxisIndex: 2, data: data.map(d => d.inverterHz), smooth: true }
    ]
  });
}

onMounted(() => {
  render();
  const onResize = () => chart && chart.resize();
  window.addEventListener('resize', onResize);
  const unwatch = watch(() => store.history.length, () => render());
  onUnmounted(() => { window.removeEventListener('resize', onResize); unwatch(); chart?.dispose(); chart = null; });
});
</script>

<style scoped>
.title { margin: 0 0 8px; font-size: 16px; }
.chart { width: 100%; height: 320px; background: #fff; border: 1px solid #e5e7eb; border-radius: 8px; }
</style>



